function checkIsHave(list, info) {
  let flag = list.find((ele) => ele.id === info.id);
  if (flag) {
    return flag;
  } else {
    return false;
  }
}
export default {
  namespaced: true,
  state: {
    shopCarList: [],
    overNum: null,
  },
  getters: {
    allInfo(state) {
      let price = 0;
      let num = 0;
      state.shopCarList.forEach((ele) => {
        price += ele.num * ele.price;
        num += ele.num;
      });
      return { price, num };
    },
  },
  mutations: {
    addShopCarList(state, payload) {
      const { name, id, price, msg, stock } = payload;
      const flag = checkIsHave(state.shopCarList, payload);
      console.log(flag.num, stock);
      if (!flag) {
        state.shopCarList.push({
          name,
          id,
          num: 1,
          price,
          msg,
          stock: stock - 1,
        });
      } else {
        if (stock > 0 || flag.num < stock) {
          console.log(flag.num, stock);
          flag.stock--;
          flag.num++;
        }
      }
    },
    reduceShopCarList(state, payload) {
      // const flag = state.shopCarList.find((ele) => ele.id === payload.id).num;
      if (payload.num > 1) {
        state.shopCarList.find((ele) => ele.id === payload.id).num--;
        state.shopCarList.find((ele) => ele.id === payload.id).stock++;
      } else {
        console.log("不能再减了");
        return false;
      }
    },
  },
};
